package com.gzpi.hwgggh.service.impl;

import com.alibaba.fastjson.JSON;
import com.gzpi.hwgggh.entity.*;
import com.gzpi.hwgggh.mapper.DWFJMapper;
import com.gzpi.hwgggh.mapper.DWXMapper;
import com.gzpi.hwgggh.mapper.GGPMapper;
import com.gzpi.hwgggh.service.DWFJService;
import com.gzpi.hwgggh.sysenum.EnumErrorCode;
import com.gzpi.hwgggh.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.events.Event;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @date : 2021-01-21 19:49
 **/
@Service
@Transactional
public class DWFJServiceImpl implements DWFJService {

    @Autowired
    private DWFJMapper dwfjMapper;

    @Autowired
    private DWXMapper dwxMapper;

    @Autowired
    private GGPMapper ggpMapper;

    @Override
    public Result getDWFJByMap(String dwxid) {
        if (StringUtils.isNotBlank(dwxid)){
            Map<String,Object> map = new HashMap<>(); //map条件
            map.put("FID",dwxid);
            DWFJ dwfj = dwfjMapper.selectDWFJBandSzrXGListByMap(map); //获取已有附件信息
            map.put("ID",dwxid);
            String xh = dwxMapper.selectDWXH(dwxid);
            DWX dwx = dwxMapper.selectDWXBandGgpXGListByMap(map);// 获取点位信息
            if (dwfj==null) {
                dwfj = new DWFJ();
                List<GGP> xzggps = dwx.getXzggps();
                List<GGP> ghggps = dwx.getGhggps();
                String ID = CommonTools.getCurrentTimeMillis();//附件新ID
                dwfj.setID(ID);
                dwfj.setFID(dwx.getID());
                if (xzggps != null && xzggps.size() > 0) {
                    List<SZRX> szrxes = new ArrayList<>();
                    for (GGP xzggp : xzggps) {
                        SZRX szrx = new SZRX();
                        szrx.setGGBH(xzggp.getGGBH());
                        szrx.setID(CommonTools.getCurrentTimeMillis());
                        szrx.setFID(ID);//设置人外键
                        szrx.setGGFID(xzggp.getID());
                        szrxes.add(szrx);
                    }
                    dwfj.setSzrxs(szrxes);
                }
                if (ghggps != null && ghggps.size() > 0) {
                    List<SZRG> szrgs = new ArrayList<>();
                    for (GGP ghggp : ghggps) {
                        SZRG szrg = new SZRG();
                        szrg.setGGBH(ghggp.getGGBH());
                        szrg.setID(CommonTools.getCurrentTimeMillis());
                        szrg.setFID(ID);
                        szrg.setGGFID(ghggp.getID());
                        szrgs.add(szrg);
                    }
                    dwfj.setSzrgs(szrgs);
                }
            }else{
                int szrg = dwfj.getSzrgs().size(); //规划设置人集合长度
                int ghggp = dwx.getGhggps().size(); //规划广告牌集合长度
                if (szrg<ghggp){//规划设置人长度 小于 规划广告牌集合长度
                    dwfj.setSzrgs(newSZRGList(dwfj.getSzrgs(),dwx.getGhggps(),dwfj.getID()));//获取新规划设置人信息
                }

                int szrx = dwfj.getSzrxs().size();
                int xzggp = dwx.getXzggps().size();
                if (szrx<xzggp){
                    dwfj.setSzrxs(newSZRXList(dwfj.getSzrxs(),dwx.getXzggps(),dwfj.getID()));
                }
            }
            dwfj.setDWBH(dwx.getXSDWBH());
            if (xh!=null) dwfj.setXH(xh);
            return Result.createSuccess(EnumErrorCode.SUCCESS_MESSAGE.toString("成功"),dwfj);
        }
        return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("参数不能为空"));
    }

    /**
     * 存在新规划设置人
     * @param szrgs
     * @param ghggp
     * @return
     */
    private List<SZRG> newSZRGList(List<SZRG> szrgs,List<GGP> ghggp,String fjid){
        List<SZRG> szrgList = szrgs; //保存返回值
        for (GGP ggp : ghggp) { //遍历广告牌集合
            boolean isExist = false; //设置人广告牌编号 是否存在 广告牌编号
            String id = ggp.getGGBH();
            for (SZRG szrg : szrgs) {
                if (szrg.getGGBH().equals(id)){
                    isExist = true; //存在
                    break;
                }
            }
            if (!isExist){ //不存在
                SZRG szrg = new SZRG();
                szrg.setGGBH(ggp.getGGBH());
                szrg.setFID(fjid);
                szrg.setID(CommonTools.getCurrentTimeMillis());
                szrg.setGGFID(ggp.getID());
                szrgList.add(szrg); //追加到返回值上
            }
        }
        return szrgList;
    }

    /**
     * 存在新现状设置人信息
     * @param szrxes
     * @param xzggp
     * @return
     */
    private List<SZRX> newSZRXList(List<SZRX> szrxes,List<GGP> xzggp,String fjid){
        List<SZRX> szrxList = szrxes; //保存返回值
        for (GGP ggp : xzggp) { //遍历广告牌集合
            boolean isExist = false; //设置人广告牌编号 是否存在 广告牌编号
            String id = ggp.getGGBH();
            for (SZRX szrg : szrxes) {
                if (szrg.getGGBH().equals(id)){
                    isExist = true; //存在
                    break;
                }
            }
            if (!isExist){ //不存在
                SZRX szrg = new SZRX();
                szrg.setGGBH(ggp.getGGBH());
                szrg.setID(CommonTools.getCurrentTimeMillis());
                szrg.setFID(fjid);
                szrg.setGGFID(ggp.getID());
                szrxList.add(szrg); //追加到返回值上
            }
        }
        return szrxList;
    }

    @Override
    public Result updateDWFJ(MultipartFile[] files, String dwfjJson, HttpServletRequest request) {
        //json数据转对象
        DWFJ dwfj = JSON.parseObject(dwfjJson, DWFJ.class);
        List<String> deleteFiles = new ArrayList<>();
        String dwfjid = dwfj.getID()!=null?dwfj.getID():CommonTools.getCurrentTimeMillis();
        boolean isA = false; //判断是否有
        if (dwfj!=null){
            Map<String,Object> map = new HashMap<>();
            map.put("ID",dwfjid);
            DWFJ orDwfj = null;
            if (dwfjMapper.selectDWFJCountByMap(map)>0){
                orDwfj = dwfjMapper.selectDWFJBandSzrXGListByMap(map); //获取已有附件信息
                isA = true;
            }

            if(files.length>0) {
                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));//去除后缀
                    String ggpid = fileName.substring(fileName.indexOf("(")+1,fileName.indexOf(")"));//截取广告编号

                    FileResult fileResult = FileUtil.saveFileToPath(request, file, HwggConstants.SAVE_PATH + dwfj.getFID() +  "/FJ", HwggConstants.MAPPING_PATH + dwfj.getFID() +"/FJ",fileName);
                    if (!fileResult.isFlag()){
                        return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("保存文件失败"));
                    }
                    List<SZRX> dwfjSzrxs= dwfj.getSzrxs();
                    List<SZRG> dwfjSzrgs = dwfj.getSzrgs();

                    String urlFileName = fileResult.getHttpUrl();
                    urlFileName = urlFileName.substring(urlFileName.lastIndexOf("/") + 1);

                    if(fileName.startsWith("QTFJ")){
                        dwfj.setQTSM(fileResult.getHttpUrl()); //保存其他附件路径
                        if (isA)
                            if (StringUtils.isNotBlank(orDwfj.getQTSM())){
                                String filename = orDwfj.getQTSM().substring(orDwfj.getQTSM().lastIndexOf("/")+1); //获取已有相关图纸路径
                                if (!urlFileName.equals(filename)) deleteFiles.add(filename);//保存要删除的文件名
                            }
                    }else if (fileName.indexOf("XGTZ")==0){
                        dwfj.setXGTZ(fileResult.getHttpUrl()); //保存相关图纸路径
                        if (isA)
                            if (StringUtils.isNotBlank(orDwfj.getXGTZ())){
                                String filename = orDwfj.getXGTZ().substring(orDwfj.getXGTZ().lastIndexOf("/")+1); //获取已有相关图纸路径
                                if (!urlFileName.equals(filename)) deleteFiles.add(filename);//保存要删除的文件名
                            }

                    }else if (fileName.indexOf("X")==0){
                        if (dwfjSzrxs!=null)
                            for (SZRX szrx : dwfjSzrxs) {
                                if (ggpid.equals(szrx.getGGFID())){ //判断该文件是属于哪个广告牌
                                    szrx.setGGPZJ(fileResult.getHttpUrl());
                                    break;
                                }
                            }

                        if (isA && orDwfj.getSzrxs()!=null && orDwfj.getSzrxs().size()>0)
                            for (SZRX orDwfjSzrx : orDwfj.getSzrxs()) {
                                if (ggpid.equals(orDwfjSzrx.getGGPZJ()) && orDwfjSzrx.getGGPZJ()!=null){
                                    String filename = orDwfjSzrx.getGGPZJ().substring(orDwfjSzrx.getGGPZJ().lastIndexOf("/")+1); //截取文件名
                                    if (!urlFileName.equals(filename))  deleteFiles.add(filename);//保存要删除的文件名
                                    break;
                                }

                            }


                    }else if (fileName.indexOf("G")==0){
                        if (dwfjSzrgs!=null)
                            for (SZRG szrg : dwfjSzrgs) {
                                if (ggpid.equals(szrg.getGGFID())){ //判断该文件是属于哪个广告牌
                                    szrg.setGGPZJ(fileResult.getHttpUrl());
                                    break;
                                }
                            }
                        if (isA && orDwfj.getSzrgs()!=null && orDwfj.getSzrgs().size()>0)
                            for (SZRG orDwfjSzrg : orDwfj.getSzrgs()) {
                                if (ggpid.equals(orDwfjSzrg.getGGFID()) && orDwfjSzrg.getGGPZJ()!=null){
                                    String filename = orDwfjSzrg.getGGPZJ().substring(orDwfjSzrg.getGGPZJ().lastIndexOf("/")+1);//截取文件名
                                    if (!urlFileName.equals(filename))  deleteFiles.add(filename);//保存要删除的文件名
                                    break;
                                }
                            }
                    }
                }
            }

            if (dwfjMapper.selectDWFJisExist(dwfj.getID())>0){
                dwfjMapper.updateDWFJ(dwfj);
            }else{
                dwfjMapper.insertDWFJ(dwfj);
            }

            for (SZRX szrx : dwfj.getSzrxs()) {
                if (dwfjMapper.selectSZRXisExist(dwfj.getID(),szrx.getID())>0){
                    dwfjMapper.updateSZRX(szrx);
                }else {
                    szrx.setFID(dwfj.getID());
                    dwfjMapper.insertSZRX(szrx);
                }
            }
            for (SZRG szrg : dwfj.getSzrgs()) {
                if (dwfjMapper.selectSZRGisExist(dwfj.getID(),szrg.getID())>0){
                    dwfjMapper.updateSZRG(szrg);
                }else {
                    szrg.setFID(dwfj.getID());
                    dwfjMapper.insertSZRG(szrg);
                }
            }

            if (deleteFiles.size()>0) {
                for (String filename : deleteFiles) {
                    FileUtil.deleteFile(request, filename, HwggConstants.SAVE_PATH + dwfj.getFID() + "/FJ");
                }
            }
            return Result.createSuccess(EnumErrorCode.SUCCESS_MESSAGE.toString("保存成功"));
        }
        return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("参数不能为空。"));
    }


}
